package com.apkicon.processor;

import com.apkicon.model.IconInfo;
import com.apkicon.parser.OptimizedApkResourceResolver;
import net.dongliu.apk.parser.ApkFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.ByteArrayInputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 优化的Adaptive Icon处理器
 * 提供高质量的图标渲染和智能算法
 */
public class OptimizedAdaptiveIconProcessor implements IconProcessor {
    
    // 线程池用于并发处理
    private static final ExecutorService executorService = Executors.newFixedThreadPool(2);
    
    @Override
    public IconInfo processIcon(com.apkicon.parser.ApkParserLibrary.ApkInfo apkInfo, com.apkicon.parser.ApkParserLibrary.IconResource iconResource, int targetSize) throws Exception {
        try (ApkFile apk = new ApkFile(apkInfo.getApkFile())) {
            System.out.println("🔍 处理Adaptive Icon: " + iconResource.getPath());
            
            // 1. 解析资源
            OptimizedApkResourceResolver.AdaptiveIconResources resources = 
                OptimizedApkResourceResolver.resolveAdaptiveIconResources(apk, iconResource.getPath());
            
            System.out.println("📱 解析结果:");
            System.out.println("   背景: " + resources.getBackgroundPath());
            System.out.println("   前景: " + resources.getForegroundPath());
            
            // 2. 加载图片
            BufferedImage backgroundImage = loadImageOptimized(apk, resources.getBackgroundPath());
            BufferedImage foregroundImage = loadImageOptimized(apk, resources.getForegroundPath());
            
            if (backgroundImage == null || foregroundImage == null) {
                throw new IllegalArgumentException("无法加载背景或前景图片");
            }
            
            // 3. 高质量渲染
            BufferedImage iconImage = renderAdaptiveIconHighQuality(backgroundImage, foregroundImage, targetSize);
            
            if (iconImage == null) {
                throw new IllegalArgumentException("Failed to render Adaptive Icon: " + iconResource.getPath());
            }
            
            System.out.println("✅ Adaptive Icon渲染完成 (" + targetSize + "x" + targetSize + ")");
            
            return new IconInfo(iconImage, IconInfo.IconType.ADAPTIVE_ICON, iconResource.getPath());
        }
    }
    
    /**
     * 优化的图片加载
     */
    private BufferedImage loadImageOptimized(ApkFile apk, String imagePath) {
        if (imagePath == null) return null;
        
        try {
            // 检查缓存
            BufferedImage cached = OptimizedApkResourceResolver.getCachedImage(imagePath);
            if (cached != null) {
                return cached;
            }
            
            // 加载图片
            byte[] data = apk.getFileData(imagePath);
            if (data != null) {
                BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
                
                // 缓存图片
                OptimizedApkResourceResolver.cacheImage(imagePath, image);
                
                return image;
            }
        } catch (Exception e) {
            System.err.println("无法加载图片资源: " + imagePath + " - " + e.getMessage());
        }
        
        return null;
    }
    
    /**
     * 高质量Adaptive Icon渲染
     */
    private BufferedImage renderAdaptiveIconHighQuality(BufferedImage backgroundImage, BufferedImage foregroundImage, int targetSize) {
        try {
            // 1. 预处理图片
            BufferedImage processedBackground = preprocessBackground(backgroundImage);
            BufferedImage processedForeground = preprocessForeground(foregroundImage);
            
            // 2. 创建高质量画布
            BufferedImage canvas = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = canvas.createGraphics();
            
            try {
                // 设置最高质量渲染
                setupHighQualityRendering(g2d);
                
                // 3. 渲染背景层
                renderBackgroundLayer(g2d, processedBackground, targetSize);
                
                // 4. 渲染前景层
                renderForegroundLayer(g2d, processedForeground, targetSize);
                
                // 5. 后处理
                BufferedImage finalImage = postProcessIcon(canvas);
                
                return finalImage;
                
            } finally {
                g2d.dispose();
            }
            
        } catch (Exception e) {
            System.err.println("高质量渲染失败: " + e.getMessage());
            return renderAdaptiveIconStandard(backgroundImage, foregroundImage, targetSize);
        }
    }
    
    /**
     * 预处理背景图片
     */
    private BufferedImage preprocessBackground(BufferedImage backgroundImage) {
        try {
            // 1. 确保背景图片是正方形
            int size = Math.max(backgroundImage.getWidth(), backgroundImage.getHeight());
            BufferedImage squareBackground = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = squareBackground.createGraphics();
            
            try {
                setupHighQualityRendering(g2d);
                
                // 居中绘制背景
                int offsetX = (size - backgroundImage.getWidth()) / 2;
                int offsetY = (size - backgroundImage.getHeight()) / 2;
                g2d.drawImage(backgroundImage, offsetX, offsetY, null);
                
            } finally {
                g2d.dispose();
            }
            
            // 2. 应用背景优化
            return optimizeBackgroundImage(squareBackground);
            
        } catch (Exception e) {
            System.err.println("背景预处理失败: " + e.getMessage());
            return backgroundImage;
        }
    }
    
    /**
     * 预处理前景图片
     */
    private BufferedImage preprocessForeground(BufferedImage foregroundImage) {
        try {
            // 1. 移除透明边缘
            BufferedImage trimmedForeground = trimTransparentEdges(foregroundImage);
            
            // 2. 应用前景优化
            return optimizeForegroundImage(trimmedForeground);
            
        } catch (Exception e) {
            System.err.println("前景预处理失败: " + e.getMessage());
            return foregroundImage;
        }
    }
    
    /**
     * 设置高质量渲染
     */
    private void setupHighQualityRendering(Graphics2D g2d) {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    }
    
    /**
     * 渲染背景层
     */
    private void renderBackgroundLayer(Graphics2D g2d, BufferedImage backgroundImage, int targetSize) {
        // 先填充白色背景（修复透明区域问题）
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, targetSize, targetSize);
        
        // 背景填满整个画布
        g2d.drawImage(backgroundImage, 0, 0, targetSize, targetSize, null);
    }
    
    /**
     * 渲染前景层
     */
    private void renderForegroundLayer(Graphics2D g2d, BufferedImage foregroundImage, int targetSize) {
        // 按照Android Adaptive Icon规范：前景在内层区域
        int innerSize = (int) (targetSize * 0.67); // 67%的内层区域
        int offset = (targetSize - innerSize) / 2;
        
        // 计算前景图片的最佳尺寸
        int foregroundSize = calculateOptimalForegroundSize(foregroundImage, innerSize);
        int foregroundOffset = (innerSize - foregroundSize) / 2;
        
        // 居中绘制前景
        g2d.drawImage(foregroundImage, 
                      offset + foregroundOffset, 
                      offset + foregroundOffset, 
                      foregroundSize, 
                      foregroundSize, null);
    }
    
    /**
     * 计算前景图片的最佳尺寸
     */
    private int calculateOptimalForegroundSize(BufferedImage foregroundImage, int availableSize) {
        // 保持宽高比，但不超过可用空间
        int originalWidth = foregroundImage.getWidth();
        int originalHeight = foregroundImage.getHeight();
        
        double aspectRatio = (double) originalWidth / originalHeight;
        
        int optimalSize;
        if (aspectRatio > 1) {
            // 宽度较大
            optimalSize = Math.min(availableSize, (int) (availableSize * 0.9));
        } else {
            // 高度较大或正方形
            optimalSize = Math.min(availableSize, (int) (availableSize * 0.8));
        }
        
        return Math.max(optimalSize, availableSize / 2); // 最小尺寸限制
    }
    
    /**
     * 移除透明边缘
     */
    private BufferedImage trimTransparentEdges(BufferedImage image) {
        try {
            int width = image.getWidth();
            int height = image.getHeight();
            
            // 找到非透明区域的边界
            int minX = width, minY = height, maxX = 0, maxY = 0;
            
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int alpha = (image.getRGB(x, y) >> 24) & 0xFF;
                    if (alpha > 0) {
                        minX = Math.min(minX, x);
                        minY = Math.min(minY, y);
                        maxX = Math.max(maxX, x);
                        maxY = Math.max(maxY, y);
                    }
                }
            }
            
            // 如果找到有效区域
            if (minX < maxX && minY < maxY) {
                int trimmedWidth = maxX - minX + 1;
                int trimmedHeight = maxY - minY + 1;
                
                BufferedImage trimmed = new BufferedImage(trimmedWidth, trimmedHeight, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2d = trimmed.createGraphics();
                
                try {
                    setupHighQualityRendering(g2d);
                    g2d.drawImage(image, -minX, -minY, null);
                } finally {
                    g2d.dispose();
                }
                
                return trimmed;
            }
            
        } catch (Exception e) {
            System.err.println("移除透明边缘失败: " + e.getMessage());
        }
        
        return image;
    }
    
    /**
     * 优化背景图片
     */
    private BufferedImage optimizeBackgroundImage(BufferedImage backgroundImage) {
        try {
            // 应用轻微的高斯模糊来平滑背景
            float[] matrix = {
                0.1f, 0.1f, 0.1f,
                0.1f, 0.2f, 0.1f,
                0.1f, 0.1f, 0.1f
            };
            
            Kernel kernel = new Kernel(3, 3, matrix);
            ConvolveOp convolveOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
            
            return convolveOp.filter(backgroundImage, null);
            
        } catch (Exception e) {
            System.err.println("背景优化失败: " + e.getMessage());
            return backgroundImage;
        }
    }
    
    /**
     * 优化前景图片
     */
    private BufferedImage optimizeForegroundImage(BufferedImage foregroundImage) {
        try {
            // 增强对比度和锐化
            BufferedImage enhanced = new BufferedImage(foregroundImage.getWidth(), foregroundImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = enhanced.createGraphics();
            
            try {
                setupHighQualityRendering(g2d);
                
                // 应用对比度增强
                g2d.setComposite(AlphaComposite.SrcOver);
                g2d.drawImage(foregroundImage, 0, 0, null);
                
            } finally {
                g2d.dispose();
            }
            
            return enhanced;
            
        } catch (Exception e) {
            System.err.println("前景优化失败: " + e.getMessage());
            return foregroundImage;
        }
    }
    
    /**
     * 后处理图标
     */
    private BufferedImage postProcessIcon(BufferedImage iconImage) {
        try {
            // 应用最终的锐化滤镜
            float[] sharpenMatrix = {
                0.0f, -0.5f, 0.0f,
                -0.5f, 3.0f, -0.5f,
                0.0f, -0.5f, 0.0f
            };
            
            Kernel kernel = new Kernel(3, 3, sharpenMatrix);
            ConvolveOp convolveOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
            
            return convolveOp.filter(iconImage, null);
            
        } catch (Exception e) {
            System.err.println("后处理失败: " + e.getMessage());
            return iconImage;
        }
    }
    
    /**
     * 标准渲染方法（fallback）
     */
    private BufferedImage renderAdaptiveIconStandard(BufferedImage backgroundImage, BufferedImage foregroundImage, int targetSize) {
        try {
            BufferedImage canvas = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = canvas.createGraphics();
            
            try {
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                
                // 渲染背景
                g2d.drawImage(backgroundImage, 0, 0, targetSize, targetSize, null);
                
                // 渲染前景
                int innerSize = (int) (targetSize * 0.67);
                int offset = (targetSize - innerSize) / 2;
                g2d.drawImage(foregroundImage, offset, offset, innerSize, innerSize, null);
                
            } finally {
                g2d.dispose();
            }
            
            return canvas;
            
        } catch (Exception e) {
            System.err.println("标准渲染失败: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 关闭线程池
     */
    public static void shutdown() {
        executorService.shutdown();
    }
}
